<?php

namespace App\Http\Requests\Admin;

use App\Models\Setting;
use Illuminate\Foundation\Http\FormRequest;

class SettingRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $type = Setting::SETTINGS;

        switch ($this->method()) {
            case 'PUT':
            case 'PATCH':
                return [
                    'cn_name' => ['required', 'string', 'between:1,20'],
                    'value' => ['array', function ($attr, $value, $fail) use ($type) {
                        // 获取该类型下对应的键
                        $valueKeys = array_keys($type[$this->route('setting')] ?? []);

                        // 判断键是否缺少
                        if (!empty(array_diff($valueKeys,array_keys($value)))) {
                            $fail('不可删除系统字段');
                        }

                        // 判断键是否增加
                        if (!empty(array_diff(array_keys($value),$valueKeys))) {
                            $fail('不可增加系统字段');
                        }
                    }]
                ];
        }
    }
}
